<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\business\UserBusiness;
use app\api\server\Token;
use app\model\FindUser;
use think\Request;
use app\model\User as UserModel;

class User
{

    /**
     * 注册
     * @return \support\Response|\think\response\Json
     */
    public function register(){
        # 判断该手机号是否注册

        return responses();
    }

    /**
     * 静默授权登录
     */
    public function authLogin(){
        $code = \request()->get('code');

        $appid = 'wxb476f68c15de9b8b';
        $appSecret = "3794b3905faf84945361913fd8feb38d";

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";

        //file_get_contents/curl
        $data = file_get_contents($url);
        $data = json_decode($data,true);
        if (isset($data['errcode'])) {
            return responses([],$data['errcode'],'服务异常、请刷新后重试');
        }

        $data['avatar'] = \request()->get('avatar');
        $data['nickname'] = \request()->get('nickname');
        $data = UserBusiness::authLogin($data);

        return responses($data,200,'ok');

    }

    /**
     * 登录
     */
    public function login(){
// echo encrypt_password('2006a');die();
        $name = \request()->post('name');
        $password = \request()->post('password');

        $info = UserModel::where("username",$name)->find();
        if (empty($info)) {
            return  responses([],'2001',"用户名不存在");
        }
  
        if ($info->password != encrypt_password($password)) {
            return responses([],2002,"密码错误");
        }
        $data = [
            'token' => Token::createToken($info->id),
            'userInfo' => [
                'id' => $info->id,
                'name' => $info->username,
                'phone' => $info->phone,
            ],
        ];

        return responses($data);
    }

    /**
     * 我的关注
     */
    public function myFollow(){
        $uid = \request()->uid;

        $data = FindUser::where("user_id",'=',$uid)->paginate(10)->toArray();
        $find_ids = array_column($data['data'],"find_id",NULL);
        $findList = \app\model\Find::whereIn('id',$find_ids)->select();
        $data['data'] = $findList;
        return responses($data);
    }






}
